package com.shopping.util;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 张衍斌
 * @version 1.0
 * @program dada-shopping
 * @description ID流水号生成器
 * @create 2019-08-06 14:13
 */
public class PrimaryGenerateUtil {
    // 流水号格式
    private static final String SERIAL_NUMBER = "XXXX";
    private static PrimaryGenerateUtil primaryGenerate = null;
    private PrimaryGenerateUtil() {
    }
    /**
     * 取得PrimaryGenerate的单例实现
     *
     * @return
     */
    public static PrimaryGenerateUtil getInstance() {
        if (primaryGenerate == null) {
            synchronized (PrimaryGenerateUtil.class) {
                if (primaryGenerate == null) {
                    primaryGenerate = new PrimaryGenerateUtil();
                }
            }
        }
        return primaryGenerate;
    }
    /**
     * 生成下一个编号
     */
    public synchronized String generateNextNumber(String sno) {
        String id = null;
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        if (sno == null) {
            id = formatter.format(date) + "0001";
        } else {
            int count = SERIAL_NUMBER.length();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < count; i++) {
                sb.append("0");
            }
            DecimalFormat df = new DecimalFormat("0000");
            id = formatter.format(date)
                    + df.format(1 + Integer.parseInt(sno.substring(1, 3)));
        }
        return id;
    }
}
